﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace IronSharePoint.Administration
{
    public class IronJobDefinition : SPJobDefinition
    {
        public IronJobDefinition(): base()
        {
        }
      
        public IronJobDefinition(string jobName, SPService service, SPServer server, SPJobLockType targetType)
           : base (jobName, service, server, targetType) 
        {
        }

        public IronJobDefinition(string jobName, SPWebApplication webApplication)
            : base (jobName, webApplication, null, SPJobLockType.ContentDatabase) 
        {
        }

        public override void Execute(Guid targetInstanceId)
        {
            IronScriptEngine engine = new IronScriptEngine();

            engine.CompileScriptFrom(ScriptPath);

            engine.Scope.SetVariable("self", this);

            if (engine.Scope.ContainsVariable("Execute"))
            {
                object method = engine.Scope.GetVariable("Execute");
                engine.Operations.Call(method, targetInstanceId);
            }
        }

        public string ScriptPath
        {
            get
            {
                return this.Properties["ScriptPath"] as String;
            }
            set
            {
                this.Properties["ScriptPath"] = value;
            }
        }
    }
}
